package com.taiyuan.ty.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.taiyuan.ty.entity.PlaceLike;
import com.taiyuan.ty.mapper.PlaceLikeMapper;
import com.taiyuan.ty.mapper.PlaceMapper;
import com.taiyuan.ty.service.PlaceLikeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @author : 周桓宇
 * @description : 点赞服务实现类
 * @createDate : 2025/3/26 下午8:30
 */
@Service
public class PlaceLikeServiceImpl extends ServiceImpl<PlaceLikeMapper, PlaceLike> implements PlaceLikeService {

    @Autowired
    private PlaceLikeMapper placeLikeMapper;

    @Autowired
    private PlaceMapper placeMapper; // 注入PlaceMapper用于更新like_count

    /**
     * 点赞
     * @param placeId 地点ID
     * @param userId 用户ID
     * @return 是否成功
     */
    @Transactional
    public boolean likePlace(Long placeId, Long userId) {
        PlaceLike placeLike = new PlaceLike();
        placeLike.setPlaceId(placeId);
        placeLike.setUserId(userId);
        placeLike.setCreateTime(new Date());
        int insertResult = placeLikeMapper.insert(placeLike);
        if (insertResult > 0) {
            // 如果插入成功，更新place表的like_count字段
            placeMapper.incrementLikeCount(placeId, 1);
            return true;
        }
        return false;
    }

    /**
     * 取消点赞
     * @param placeId 地点ID
     * @param userId 用户ID
     * @return 是否成功
     */
    @Transactional
    public boolean unlikePlace(Long placeId, Long userId) {
        int deleteResult = placeLikeMapper.delete(new QueryWrapper<PlaceLike>()
                .eq("place_id", placeId)
                .eq("user_id", userId));
        if (deleteResult > 0) {
            // 如果删除成功，更新place表的like_count字段
            placeMapper.incrementLikeCount(placeId, -1);
            return true;
        }
        return false;
    }

    /**
     * 获取点赞数
     * @param placeId 地点ID
     * @return 点赞数
     */
    public int getPlaceLikesCount(Long placeId) {
        return placeLikeMapper.selectCount(new QueryWrapper<PlaceLike>()
                .eq("place_id", placeId));
    }
}